package cn.klaw.database.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import cn.klaw.database.util.TenantDataSourceUtil;
import cn.klaw.util.UserProvider;
import cn.klaw.constant.GlobalConst;
import cn.klaw.util.DateUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 *
 * @version V3.1.0
 *
 * @date 2020年12月22日 下午20:14
 */
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        String userId = UserProvider.getLoginUserId();
        Object enabledMark = this.getFieldValByName("enabledMark", metaObject);
        Object creatorUserId = this.getFieldValByName("creatorUserId", metaObject);
        Object creatorTime = this.getFieldValByName("creatorTime", metaObject);
        Object creatorUser = this.getFieldValByName("creatorUser", metaObject);
        if (enabledMark == null) {
            this.strictInsertFill(metaObject, "enabledMark", () -> 1, Integer.class);
        }
        if (creatorUserId == null) {
            this.strictInsertFill(metaObject, "creatorUserId", () -> userId, String.class);
        }
        if (creatorTime == null) {
            this.strictInsertFill(metaObject, "creatorTime", DateUtil::getNowDate, Date.class);
        }
        if (creatorUser == null) {
            this.strictInsertFill(metaObject, "creatorUser", () -> userId, String.class);
        }
        String tenantColumn = TenantDataSourceUtil.getTenantColumn();
        if (GlobalConst.DEFAULT_TENANT_VALUE.equals(tenantColumn)) {
            this.strictInsertFill(metaObject, "tenantId", () -> tenantColumn, String.class);
        } else {
            this.setFieldValByName("tenantId", TenantDataSourceUtil.getTenantColumn(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userId = UserProvider.getLoginUserId();
        this.strictUpdateFill(metaObject, "lastModifyTime", DateUtil::getNowDate, Date.class);
        this.strictUpdateFill(metaObject, "lastModifyUserId", () -> userId, String.class);
        this.strictUpdateFill(metaObject, "lastModifyUser", () -> userId, String.class);
        String tenantColumn = TenantDataSourceUtil.getTenantColumn();
        if (GlobalConst.DEFAULT_TENANT_VALUE.equals(tenantColumn)) {
            this.strictUpdateFill(metaObject, "tenantId", () -> tenantColumn, String.class);
        } else {
            this.setFieldValByName("tenantId", TenantDataSourceUtil.getTenantColumn(), metaObject);
        }
    }


}
